package com.xzx.springmvc.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/5/11 21:22
 */
@Slf4j
@Controller
public class AsyncController {

    @ResponseBody
    @GetMapping("/async/v1")
    public Callable<String> helloCallable() {
        log.info("主线程开始:{}", Thread.currentThread().getName());
        Callable<String> result = () -> {
            log.info("副线程开始:{}", Thread.currentThread().getName());
            Thread.sleep(30000);
            log.info("副线程结束:{}", Thread.currentThread().getName());
            return "sync success";
        };
        log.info("主线程结束:{}", Thread.currentThread().getName());
        return result;
    }


    @ResponseBody
    @GetMapping("/async/v2")
    public DeferredResult<String> helloDeferResult() {
        // 先立即返回一个DeferredResult对象，这个时候SpringMvc不会立即响应，而是等待为这个对象上设置数据，当设置数据后，才会立即响应
        DeferredResult<String> result = new DeferredResult<>();
        // 记录下这个对象，由由有其他线程来设置
        new Thread(() -> {
            try {
                Thread.sleep(30000L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // 其他线程设置结果后springMvc会响应这个结果
            result.setResult("DeferredResult async success");
        }).start();
        return result;
    }
}
